from django.shortcuts import render
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import viewsets, parsers
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated, IsAdminUser

from book.models import Book
from book.serializers import BookSerializer
from account.models import Profile


# Create your views here.
class CollectViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    permission_classes = [IsAuthenticated]
    parser_classes = [parsers.MultiPartParser, parsers.FormParser, parsers.JSONParser]

    def get_permissions(self):
        if self.request.method in ['PUT', 'PATCH']:
            return [IsAdminUser()]
        return [IsAuthenticated()]
    
    def list(self, request):
        user = request.user
        profile = Profile.objects.get(user=user)
        books = profile.collect_books.all()
        serializer = BookSerializer(books, many=True, context={'request': request})
        return Response(serializer.data)

    def create(self, request):
        user = request.user
        profile = Profile.objects.get(user=user)
        book_id = request.data['book_id']
        try:
            book = Book.objects.get(id=book_id)
            profile.collect_books.add(book)
            return Response({
                'status_code': 0,
                'message': '收藏成功'
            })
        except ObjectDoesNotExist:
            return Response({
                'message': '电影信息不存在'
            })
        except:
            return Response({
                'message': '收藏失败'
            })

    def destroy(self, request, pk):
        user = request.user
        profile = Profile.objects.get(user=user)
        try:
            book = Book.objects.get(id=pk)
            if book not in profile.collect_books.all():
                return Response({'message': '未收藏该电影'})
            profile.collect_books.remove(book)
            return Response({'message': '取消收藏成功'})
        except ObjectDoesNotExist:
            return Response({'message': '电影信息不存在'})
        except:
            return Response({'message': '取消收藏失败'})

    @action(detail=True, methods=['get'])
    def is_collected(self, request, pk=None):
        print(request)
        user = request.user
        profile = Profile.objects.get(user=user)
        book = Book.objects.get(id=pk)
        is_collected = profile.collect_books.filter(id=book.id).exists()
        return Response({'is_collected': is_collected})


class OwnedViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    permission_classes = [IsAuthenticated]
    parser_classes = [parsers.MultiPartParser, parsers.FormParser, parsers.JSONParser]

    def get_permissions(self):
        if self.request.method in ['PUT', 'PATCH']:
            return [IsAdminUser()]
        return [IsAuthenticated()]

    def list(self, request):
        user = request.user
        profile = Profile.objects.get(user=user)
        books = profile.owned_books.all()  # 所属书籍
        serializer = BookSerializer(books, many=True, context={'request': request})
        return Response(serializer.data)

    def create(self, request):
        user = request.user
        book_id = request.data.get('book_id')  # 新增：接受book_id参数
        
        if book_id:
            # 关联已有书籍
            try:
                book = Book.objects.get(id=book_id)
                profile = Profile.objects.get(user=user)
                profile.owned_books.add(book)
                return Response({'message': '关联成功'}, status=201)
            except Book.DoesNotExist:
                return Response({'message': '书籍不存在'}, status=404)
        else:
            # 原有逻辑：创建新书并关联
            serializer = BookSerializer(data=request.data)
            if serializer.is_valid():
                book = serializer.save()
                profile = Profile.objects.get(user=user)
                profile.owned_books.add(book)
                return Response({'message': '作品创建成功'}, status=201)
            return Response(serializer.errors, status=400)

    def destroy(self, request, pk):
        user = request.user
        profile = Profile.objects.get(user=user)
        try:
            book = Book.objects.get(id=pk)
            if book not in profile.owned_books.all():
                return Response({'message': '无权操作该书籍'}, status=403)
            book.delete()  # 直接删除书籍对象
            return Response({'message': '作品删除成功'})
        except ObjectDoesNotExist:
            return Response({'message': '书籍信息不存在'}, status=404)
        except Exception as e:
            return Response({'message': '删除失败'}, status=500)

    @action(detail=True, methods=['get'])
    def is_owned(self, request, pk=None):
        user = request.user
        profile = Profile.objects.get(user=user)
        book = Book.objects.get(id=pk)
        is_owned = profile.owned_books.filter(id=book.id).exists()
        return Response({'is_owned': is_owned})